package educrypt.io;

import java.io.File;
import java.net.FileNameMap;
import java.net.URLConnection;

public class FileUtil {

	public static final String MIMETYPE_PLAINTEXT = "text/plain";
	public static final String MIMETYPE_DOC = "application/doc";
	public static final String MIMETYPE_DOCX = "application/docx";
	public static final String MIMETYPE_PDF = "application/pdf";
	public static final String MIMETYPE_UNSUPPORTED = "";

	public static final String EXTENSION_TXT = "txt";
	public static final String EXTENSION_DOC = "doc";
	public static final String EXTENSION_DOCX = "docx";
	public static final String EXTENSION_PDF = "pdf";
	public static final String EXTENSION_UNKNOWN = "";

	public static String getFileNameFromPath(String path) {
		int lastSeparatorIndex = path.lastIndexOf(File.separatorChar);
		String fileName = path.substring(lastSeparatorIndex + 1, path.length());
		return fileName;
	}

	public static String removeExtension(String fileName) {
		String fileNameWithoutExtension = fileName;
		int lastIndexOfPoint = fileName.lastIndexOf(".");

		// > 0 because .name is valid and "name" is not an extension
		boolean haveExtension = lastIndexOfPoint > 0
				&& lastIndexOfPoint < fileName.length() - 1;
		if (haveExtension) {
			fileNameWithoutExtension = fileName.substring(0, lastIndexOfPoint);
		}
		return fileNameWithoutExtension;
	}

	public static String getMimeType(String path) {

		FileNameMap fileNameMap = URLConnection.getFileNameMap();
		String type = fileNameMap.getContentTypeFor(path);
		// Fallback: mimetype from extension
		if (type == null) {
			type = getSupportedMimeTypeFromFileExtension(path);
		}
		return type;
	}

	private static String getSupportedMimeTypeFromFileExtension(String path) {
		String mimeType = MIMETYPE_UNSUPPORTED;
		String fileName = getFileNameFromPath(path);
		String extension = getFileExtension(fileName);
		if (extension.equals(EXTENSION_TXT)) {
			mimeType = MIMETYPE_PLAINTEXT;
		} else if (extension.equals(EXTENSION_PDF)) {
			mimeType = MIMETYPE_PDF;
		} else if (extension.equals(EXTENSION_DOC)) {
			mimeType = MIMETYPE_DOC;
		} else if (extension.equals(EXTENSION_DOCX)) {
			mimeType = MIMETYPE_DOCX;
		} else {
			mimeType = MIMETYPE_UNSUPPORTED;
		}
		return mimeType;

	}

	private static String getFileExtension(String fileName) {
		String extension = EXTENSION_UNKNOWN;
		int lastIndexOfPoint = fileName.lastIndexOf(".");

		// > 0 because .name is valid and "name" is not an extension
		boolean haveExtension = lastIndexOfPoint > 0
				&& lastIndexOfPoint < fileName.length() - 1;

		if (haveExtension) {
			extension = fileName.substring(lastIndexOfPoint + 1,
					fileName.length());
		}
		return extension;
	}
}
